package com.kekezu.kppw.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import com.kekezu.kppw.R;

import android.content.Context;
import android.util.Base64;

public final class RSAUtils {
	private static String RSA = "RSA";

	private static String RSA_ANDROID = "RSA/ECB/PKCS1Padding";

	// 公钥
	private static String pubKEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsvMzoWJvt5H2ih4DIevFFYCCr"
			+ "\r"
			+ "H2B4bodnxJi0WpgHzgO5YR/kUwGS71NLkHY11aO2AISpGOjk0JN3HjC/fB6Xaz8j"
			+ "\r"
			+ "b+4WnJJib4UD1U0H3/pntO4OKldL5pdNv/L5cAXR1cPzzzHAzpaPsOr6lkMkrJ61"
			+ "\r" + "aS4ZZ5tlTIfJBNFo4QIDAQAB";

	/**
	 * 用公钥解密
	 * 
	 * @param encryptedData
	 * @param publicKey
	 * @return
	 */
	public static byte[] decryptData(byte[] encryptedData, PublicKey publicKey) {
		try {
			Cipher cipher = Cipher.getInstance(RSA_ANDROID);
			cipher.init(Cipher.DECRYPT_MODE, publicKey);
			return cipher.doFinal(encryptedData);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 从字符串中加载公钥
	 * 
	 * @param publicKeyStr
	 *            公钥数据字符串
	 * @throws Exception
	 *             加载公钥时产生的异常
	 */
	public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
		try {
			byte[] buffer = Base64.decode(publicKeyStr, Base64.DEFAULT);
			KeyFactory keyFactory = KeyFactory.getInstance(RSA);
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			return (RSAPublicKey) keyFactory.generatePublic(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法");
		} catch (InvalidKeySpecException e) {
			throw new Exception("公钥非法");
		} catch (NullPointerException e) {
			throw new Exception("公钥数据为空");
		}
	}

	/**
	 * 通过公钥byte[](publicKey.getEncoded())将公钥还原，适用于RSA算法
	 * 
	 * @param keyBytes
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 */
	public static PublicKey getPublicKey(byte[] keyBytes)
			throws NoSuchAlgorithmException, InvalidKeySpecException {
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(RSA);
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}

	/**
	 * 从文件中输入流中加载公钥
	 * 
	 * @param in
	 *            公钥输入流
	 * @throws Exception
	 *             加载公钥时产生的异常
	 */
	public static PublicKey loadPublicKey(InputStream in) throws Exception {
		try {
			return loadPublicKey(readKey(in));
		} catch (IOException e) {
			throw new Exception("公钥数据流读取错误");
		} catch (NullPointerException e) {
			throw new Exception("公钥输入流为空");
		}
	}

	/**
	 * 读取密钥信息
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 */
	private static String readKey(InputStream in) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String readLine = null;
		StringBuilder sb = new StringBuilder();
		while ((readLine = br.readLine()) != null) {
			if (readLine.charAt(0) == '-') {
				continue;
			} else {
				sb.append(readLine);
				sb.append('\r');
			}
		}

		return sb.toString();
	}

	/**
	 * 打印公钥信息
	 * 
	 * @param publicKey
	 */
	public static void printPublicKeyInfo(PublicKey publicKey) {
		RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
		System.out.println("----------RSAPublicKey----------");
		System.out.println("Modulus.length="
				+ rsaPublicKey.getModulus().bitLength());
		System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
		System.out.println("PublicExponent.length="
				+ rsaPublicKey.getPublicExponent().bitLength());
		System.out.println("PublicExponent="
				+ rsaPublicKey.getPublicExponent().toString());
	}

	public static String getDecrypt(Context context) {
		String decryptStr = "";
		String strSign = context.getResources().getString(R.string.sign);
		try {
			PublicKey publicKey = loadPublicKey(pubKEY);
			byte[] decryptByte = decryptData(
					Base64.decode(strSign, Base64.DEFAULT), publicKey);
			decryptStr = new String(decryptByte);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return decryptStr;
	}
}
